<script setup lang="ts">
import { ref } from 'vue'
import router from '../../router'
import { ElMessage, FormRules } from 'element-plus'
import { usePageStore, useSystemStore, useUserStore } from '../../stores'
import { TLogin } from '../../Types/user'
import { loginService } from '../../api/login'
// import { baseURL } from '@/utils/request'
import defaultBackground from '@/assets/background/snowflakes.jpg'
// import slideVerify from '../../components/Captcha/slideVerify.vue'

// 登录表单数据
const loginForm = ref({
	account: '',
	password: ''
})
// 注册表单数据
const regForm = ref({
	account: '',
	password: '',
	repassword: '',
	user_type: '',
	uname: ''
})
const loginFormRef = ref()
// const showVerify = ref(false)
const logReg = ref(true)
const loading = ref(false)
// const defaultBackground = baseURL.replace(/\/api\/?$/, '') + '/static/background/snowflakes.jpg' // 移除路径中的/api/

// 登录
const login = async () => {
	// console.log(loginForm.value)
	loading.value = true

	// 初始化仓库信息
	const userStore = useUserStore()
	const systemStore = useSystemStore()
	userStore.removeUserInfo()
	systemStore.removeSystemTitle()

	try {
		// 数据校验
		await loginFormRef.value.validate()

		// 数据处理
		const res = await loginService(loginForm.value)
		// console.log(res.data.data)
		if (res.data.code === 1) {
			// 登录信息存入仓库
			userStore.setUserInfo(res.data.data)

			// 获取系统标题
			systemStore.getSystemTitle()

			// // 获取页面信息
			// const pageStore = usePageStore()
			// const pageResult = await pageStore.getPage()

			// if (!pageResult) {
			// 	ElMessage.error('页面数据加载失败，请重新登录')
			// 	loading.value = false
			// 	return
			// }

			// // 强制加载路由
			// try {
			// 	const { loadDynamicRoutes } = await import('@/router')
			// 	await loadDynamicRoutes()
			// 	userStore.setFirstVisit(false)
			// } catch (error) {
			// 	console.error('路由加载失败:', error)
			// 	ElMessage.warning('路由加载不完整，页面可能无法正常访问')
			// }

			// 登录成功信息
			ElMessage.success('登录成功!')
			loading.value = false

			// 转到首页
			await router.push('/')
		} else {
			// 登录失败
			ElMessage.error(res.data.msg || '登录失败，请检查账号密码')
			loading.value = false
		}
	} catch (err: any) {
		ElMessage.error('登录过程出现错误')
		console.error('登录错误:', err)
		loading.value = false
	}
}
// 回车登录
const enterLogin = () => {
	login()
}

// 表单验证规则
const rules = ref<FormRules<TLogin>>({
	account: [
		{ required: true, min: 4, max: 10, message: '请输入正确账号！', trigger: 'blur' },
		{
			pattern: /^[a-z0-9]+$/,
			message: '账号应为4-10位数字或字母！',
			trigger: 'blur'
		}
	],
	password: [
		{
			required: true,
			min: 4,
			max: 12,
			message: '请输入正确密码',
			trigger: 'blur'
		},
		{
			pattern: /^[^\u4e00-\u9fff]+$/,
			message: '密码应为 4-12位的非中文字符！',
			trigger: 'blur'
		}
	],
	repassword: [
		{ required: true, min: 4, max: 12, message: '请再次输入密码', trigger: 'blur' },
		{ message: '密码应为 4-12位的非中文字符！', trigger: 'blur' },
		{
			validator: (rule: any, value: string, callback: any) => {
				rule // 占位
				// 判断 value 和 当前 form 中收集的 password 是否一致
				if (value !== regForm.value.password) {
					callback(new Error('两次输入密码不一致'))
				} else {
					callback() // 校验成功
				}
			},
			trigger: 'blur'
		}
	],
	user_type: [{ required: true, message: '请选择您的类型！', trigger: 'blur' }],
	uname: [
		{
			required: true,
			min: 2,
			max: 4,
			message: '请输入真实姓名！',
			trigger: 'blur'
		},
		{ pattern: /^[\u4e00-\u9fa5]+$/, message: '真实姓名应为2-4位中文字符！', trigger: 'blur' }
	]
})

// 点击验证
// const onCaptch = () => {
// 	showVerify.value = true

// 	console.log('验证成功')
// }

// watch(loading, () => {
// 	setTimeout(() => {
// 		ElMessage.warning('当前网络较差')
// 	}, 10000)
// })
</script>

<template>
	<div class="page" :style="{ backgroundImage: 'url(' + defaultBackground + ')' }">
		<!-- 登录页面 -->
		<div class="form-page" v-loading="loading" v-if="logReg">
			<el-form ref="loginFormRef" :rules="rules" :model="loginForm">
				<el-form-item><h1>登录</h1></el-form-item>
				<el-form-item prop="account" label="账号：">
					<el-input
						v-model="loginForm.account"
						clearable
						placeholder="请输入6-12位的账号！"
						@keyup.enter="enterLogin"
					></el-input>
				</el-form-item>
				<el-form-item prop="password" label="密码：">
					<el-input
						v-model="loginForm.password"
						clearable
						show-password
						placeholder="请输入6-12位的密码！"
						@keyup.enter="enterLogin"
					></el-input>
				</el-form-item>
				<!-- <el-form-item class="captcha" label="验证：">
					<el-button @click="onCaptch" type="primary">点击验证</el-button>
				</el-form-item> -->
				<el-form-item class="btn-box">
					<el-button @click="login" type="primary">登录</el-button>
					<el-button type="info">清空</el-button>
				</el-form-item>
				<!-- <el-form-item>
					<div class="login-footer">
						<el-link @click="goReg" type="primary">账号未注册？去注册！</el-link>
						<el-link type="warning">忘记密码？</el-link>
					</div>
				</el-form-item> -->
			</el-form>
		</div>

		<!-- 注册页面 -->
		<!-- <div class="form-page" v-else>
			<el-form ref="regFormRef" :rules="rules" :model="regForm">
				<el-form-item><h1>注册</h1></el-form-item>
				<el-form-item prop="account" label="账号：">
					<el-input
						v-model="regForm.account"
						clearable
						placeholder="请输入8-12位的账号！"
					></el-input>
				</el-form-item>
				<el-form-item prop="password" label="密码：">
					<el-input
						v-model="regForm.password"
						clearable
						show-password
						placeholder="请输入6-12位的密码！"
					></el-input>
				</el-form-item>
				<el-form-item class="repassword" prop="repassword" label="二次密码：">
					<el-input
						v-model="regForm.repassword"
						clearable
						show-password
						placeholder="请再次输入密码！"
					></el-input>
				</el-form-item>
				<el-form-item prop="user_type" label="类型：">
					<el-radio-group v-model="regForm.user_type">
            <el-radio label="学生">学生</el-radio>
            <el-radio label="任课老师">任课老师</el-radio>
						<el-radio label="辅导员">辅导员</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item prop="uname" label="姓名：">
					<el-input v-model="regForm.uname" clearable placeholder="请输入真实姓名！"></el-input>
				</el-form-item>
				<el-form-item class="btn-box">
					<el-button @click="register" type="primary">注册</el-button>
					<el-button type="info">清空</el-button>
				</el-form-item>
				<el-form-item>
					<div class="login-footer">
						<el-link type="primary" @click="goLogin">已有密码？去登录！</el-link>
					</div>
				</el-form-item>
			</el-form>
		</div> -->

		<!-- 验证界面 -->
		<!-- <div class="verify" v-show="showVerify">
			<slideVerify width="100"></slideVerify>
		</div> -->
	</div>
</template>

<style lang="scss" scoped>
* {
	// box-sizing: border-box;
	margin: 0;
	padding: 0;
	// border: 1px solid #db1919;
}

.page {
	display: flex;
	justify-content: center;
	align-items: center;
	background-size: cover;
	height: 100%;
	.form-page {
		background: linear-gradient(129deg, #fff1eb 12.72%, #ace0f9 100%); // deg: 角度
		border-radius: 20px;
		height: auto;
		width: 30%;
		.el-form {
			display: flex;
			flex-direction: column;
			align-items: center;
			// justify-content: center;
			.el-form-item {
				// height: 50px;
				width: auto;
				margin-bottom: 15px;
				:deep(.el-form-item__label) {
					color: rgb(30, 76, 228);
				}
				h1 {
					margin: 20px 0;
					text-align: center;
				}
				.el-input {
					width: 180px;
					// border-radius: 20px;
				}
				&.repassword {
					// width: auto;
					margin-right: 28px;
				}
				&.btn-box {
					margin-top: 10px;
					.el-button {
						border-radius: 15px;
						width: 50px;
					}
				}
				// &.captcha {
				// 	position: relative;
				// 	.el-button {
				// 		display: block;
				// 		width: 200px;
				// 	}
				// 	&[v-show-true].el-button {
				// 		display: none;
				// 	}
				// }
				.el-radio-group {
					width: 180px;
					.el-radio:nth-child(2) {
						margin-left: 20px;
					}
				}
				.login-footer {
					display: flex;
					flex-wrap: nowrap;
					justify-content: flex-end;
					width: 100%;
					.el-link {
						position: relative;
						font-size: smaller;
						margin-left: 10px;
					}
				}
			}
		}
	}

	// .verify {
	// 	// position: relative;
	// 	position: absolute;
	// 	top: 0;
	// 	left: 0;
	// 	width: 100%;
	// 	height: 100%;
	// }
}
</style>
